<template>
  <view>
    <Popup @delete-confirm="deleteConfirm" ref="popup"></Popup>
    <!-- 返回按钮 -->
    <!-- <button @click="goBack" class="back-button">返回</button> -->
    <!-- <div class="taskQuery">taskQuery</div> -->
    <QueryByDate @notifyParent="getThisPageData" ref="queryDateAgain"></QueryByDate>

    <view v-for="item in pageData" :key="item.createTime">
      <uni-section :title="item.createUser" type="line">
        <text>任务创建：{{ item.createTime }}</text>
        <!-- <uni-card :cover=" cover" @click="onClick"> -->
        <uni-card>
          <!-- 普通卡片首页 -->
          <uni-card :is-shadow="false" is-full>
            <text class="uni-h6">{{ item.start }}</text>
          </uni-card>
          <!-- 普通卡片 -->
          <uni-card :is-shadow="false" is-full>
            <text class="uni-h6" :class="getActiveClass(item.status1)">{{ item.taskValve1 }}</text>
          </uni-card>
          <!-- 普通卡片 -->
          <uni-card :is-shadow="false" is-full v-if="item.taskValve2 != null">
            <text class="uni-h6" :class="getActiveClass(item.status2)">{{ item.taskValve2 }}</text>
          </uni-card>
          <!-- 普通卡片 -->
          <uni-card :is-shadow="false" is-full v-if="item.taskValve3 != null">
            <text class="uni-h6" :class="getActiveClass(item.status3)">{{ item.taskValve3 }}</text>
          </uni-card>
          <!-- 普通卡片 -->
          <uni-card :is-shadow="false" is-full v-if="item.taskValve4 != null">
            <text class="uni-h6" :class="getActiveClass(item.status4)">{{ item.taskValve4 }}</text>
          </uni-card>
          <!-- 普通卡片 -->
          <uni-card :is-shadow="false" is-full v-if="item.taskValve5 != null">
            <text class="uni-h6" :class="getActiveClass(item.status5)">{{ item.taskValve5 }}</text>
          </uni-card>
          <!-- 普通卡片 -->
          <uni-card :is-shadow="false" is-full v-if="item.taskValve6 != null">
            <text class="uni-h6" :class="getActiveClass(item.status6)">{{ item.taskValve6 }}</text>
          </uni-card>
          <!-- 普通卡片 -->
          <uni-card :is-shadow="false" is-full v-if="item.taskValve7 != null">
            <text class="uni-h6" :class="getActiveClass(item.status7)">{{ item.taskValve7 }}</text>
          </uni-card>
          <!-- 普通卡片尾页 -->
          <uni-card :is-shadow="false" is-full>
            <text class="uni-h6">{{ item.end }}</text>
          </uni-card>
          <!-- <image slot='cover' style="width: 100%;" :src="cover"></image> -->
          <text class="uni-body">任务备注：</text>
          <template v-slot:actions>
            <!--权限低的不显示  -->
            <view v-if="deletePower!.position >= 3" class="card-actions">
              <view v-if="!item.favorite" class="card-actions-item">
                <uni-icons type="star" size="18" color="#999"></uni-icons>
                <text class="card-actions-item-text" @click="favAction(item)">收藏</text>
              </view>
              <view v-else class="card-actions-item">
                <uni-icons type="star-filled" size="28" color="yellow"></uni-icons>
                <text class="card-actions-item-text" @click="delFavAction(item)">已收藏</text>
              </view>
              <view class="card-actions-item" @click="deleteTask(item)">
                <uni-icons type="trash" size="18" color="#999"></uni-icons>
                <text class="card-actions-item-text">删除</text>
              </view>
              <view class="card-actions-item" @click="actionsClick('审批')">
                <uni-icons type="flag" size="18" color="#999"></uni-icons>
                <text class="card-actions-item-text">审批</text>
              </view>
            </view>
          </template>
        </uni-card>
      </uni-section>
    </view>
  </view>
</template>

<script lang="ts" setup>
import QueryByDate from './components/QueryByDate.vue'
import Popup from './components/Popup.vue'

import type TaskQueryPage from '@/types/taskQueryPage'
import { ref, onMounted } from 'vue'
import { http } from '@/utils/http'
import type User from '@/types/user'
import type ValveTaskFavor from '@/types/ValveTaskFavor'
import { useAuthStore } from '@/stores/auth'

const deletePower = ref<User>()

// 定义返回函数
const goBack = () => {
  // 调用 uni-app 的 navigateBack 方法返回上一页
  uni.navigateBack()
}

const queryDateAgain = ref<InstanceType<typeof QueryByDate> | null>(null)
const popup = ref<InstanceType<typeof Popup> | null>(null)
// 定义一个响应式变量来存储待删除的任务对象
const taskToDelete = ref<TaskQueryPage | null>(null)

const pageData = ref<TaskQueryPage[] | null>(null)

// 定义一个函数来获取当前页面的数据，更新当前页面的数据（父组件调用）
const getThisPageData = (o: any) => {
  // 确保 res 是数组并且过滤掉 null 值
  const filteredRes = Array.isArray(o) ? o.filter((item) => item !== null) : []
  pageData.value = filteredRes as TaskQueryPage[]
  //console.log(pageData.value);
}

const authStore = useAuthStore()

const valvepage = ref<ValveTaskFavor | null>(null)
const fav = ref(false)

//点收藏执行的函数
const favAction = async (e: TaskQueryPage) => {
  //初始化valuepage
  valvepage.value = {
    end: '',
    taskValve1: '',
    taskValve2: '',
    taskValve3: '',
    taskValve4: '',
    taskValve5: '',
    taskValve6: '',
    taskValve7: '',
    start: '',
    createUser: JSON.stringify(authStore.user?.name),
    createTime: '',
    favorite: false,
  }
  console.log('收藏')
  //console.log(JSON.parse(JSON.stringify(e)));
  // 直接访问 e 的属性
  //console.log(`ID: ${e.id}`);

  //收集页面数据
  if (valvepage.value) {
    // 直接赋值，避免不必要的字符串化
    valvepage.value.start = e.start
    valvepage.value.end = e.end

    // 使用解构赋值简化代码
    const keys = [
      'taskValve1',
      'taskValve2',
      'taskValve3',
      'taskValve4',
      'taskValve5',
      'taskValve6',
      'taskValve7',
    ] as const

    keys.forEach((key) => {
      if (key in e && typeof e[key] === 'string') {
        if (valvepage.value) {
          valvepage.value[key] = e[key]
        }
      }
    })
  } else {
    console.error('valvepage is not initialized')
  }

  //console.log(JSON.parse(JSON.stringify(valvepage.value)));

  // TODO: 添加收藏逻辑,发送请求
  const res = await http<string>({
    method: 'POST',
    url: '/valve/collectTask',
    data: JSON.parse(JSON.stringify(valvepage.value)),
  })

  const flag = ref<Number>(Number.parseInt(res.data))
  //如果data为1，表示收藏成功
  if (flag.value === 1) {
    setTimeout(() => {
      // 重新获取数据，更新页面数据
      if (queryDateAgain.value && typeof queryDateAgain.value.getDataAgain === 'function') {
        queryDateAgain.value.getDataAgain()
      }
    }, 1)

    //提示
    uni.showToast({
      title: '收藏成功',
      icon: 'success',
      duration: 2000,
    })
  } else if (flag.value == -1) {
    // 重新获取数据，更新页面数据
    if (queryDateAgain.value && typeof queryDateAgain.value.getDataAgain === 'function') {
      queryDateAgain.value.getDataAgain()
    }
    uni.showToast({
      title: '您已收藏过该任务',
      icon: 'none',
      duration: 2000,
    })
  } else {
    // 收藏失败，提示错误信息
    uni.showToast({
      title: '收藏失败',
      icon: 'error',
      duration: 2000,
    })
  }
}

//取消收藏执行的函数
const delFavAction = (e: TaskQueryPage) => {
  uni.showToast({
    title: '已收藏,无法取消',
    icon: 'none',
    duration: 2000,
  })
}

onMounted(() => {
  deletePower.value = JSON.parse(uni.getStorageSync('userInfo'))
})

//弹窗删除任务
let deleteTask = async (taskObject: TaskQueryPage) => {
  // 设置待删除的任务对象
  taskToDelete.value = taskObject

  if (!popup.value || typeof popup.value.doPopup !== 'function') {
    console.error('Popup component or doPopup method not available')
    return
  }
  try {
    //弹出弹窗
    popup.value.doPopup('error')
  } catch (error) {
    console.error('Error occurred while trying to show popup or delete task:', error)
  }
}

// 确认删除后执行删除操作
const deleteConfirm = async () => {
  const task = taskToDelete.value
  if (task) {
    console.log('Confirm delete for task:', task.id)

    try {
      // 发送删除请求
      await http<string>({
        method: 'GET',
        url: '/valve/deleteTask',
        data: {
          id: task.id,
        },
      })

      // 重新获取数据，更新页面数据
      if (queryDateAgain.value && typeof queryDateAgain.value.getDataAgain === 'function') {
        queryDateAgain.value.getDataAgain()
      }

      // 清空待删除的任务对象
      taskToDelete.value = null
    } catch (error) {
      console.error('Error occurred while deleting task:', error)
    }
  }
}

const actionsClick = (e: any) => {
  console.log(e)
  uni.showToast({
    title: '此功能暂未开放',
    icon: 'error',
  })
}
// 根据任务状态返回是否应用 .active 类
const getActiveClass = (status: number) => {
  return status === 1 ? 'active' : 'uni-h6'
}
</script>

<style lang="scss">
/* 添加返回按钮的样式 */
.back-button {
  background-color: #007aff;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  margin: 10px;
}

.container {
  overflow: hidden;
}

.custom-cover {
  flex: 1;
  flex-direction: row;
  position: relative;
}

.card-actions {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  height: 45px;
  border-top: 1px #eee solid;
}

.card-actions-item {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.card-actions-item-text {
  font-size: 12px;
  color: #666;
  margin-left: 5px;
}

.cover-image {
  flex: 1;
  height: 150px;
}

.no-border {
  border-width: 0;
}

.active {
  background-color: green;
  /* 设置背景颜色为绿色 */
  color: white;
  /* 可选：设置文本颜色为白色，以便在绿色背景上清晰可见 */
  padding: 15px;
  /* 可选：设置内边距 */
  border-radius: 8px;
  /* 可选：设置圆角 */
}
</style>
